import { createStore } from 'vuex'
import persistedstate from 'vuex-persistedstate';
export default createStore({
  state: {
    cartList:[], // 购物车的数据
    history:[], // 存放历史记录
  },
  mutations: {
    addCart(state,val){ // 加入购物车数据，判断商品id是否相同
      let index = state.cartList.findIndex(item => item.product_id == val.product_id);
      if (index>-1){
        state.cartList[index].buyNum += val.buyNum
      } else {
        state.cartList.push(val);
      }
    },
    storeDel(state,i){ // 单个的删除
      state.cartList.splice(i,1);
    },
    delSome(state){ // 批量删除的方法
      state.cartList = state.cartList.filter(item => item.ischeck==false);
    },
    addHistory(state,val){
      let index = state.history.findIndex(item => item == val);
      if (index>-1){ // 判断是否重复
        state.history.splice(index,1);
      }
      if (state.history.length>4){ // 长度限制，只能有5条
        state.history.splice(4,1);
      }
      state.history.unshift(val);
    },
    delectAll(state){ // 历史记录的全部删除
      state.history = [];
    },
    delectOne(state,i){ // 历史记录的单个删除
      state.history.splice(i,1);
    }
  },
  actions: {
  },
  modules: {
  },
  plugins:[
    new persistedstate({
      storage: window.localStorage,
    }),
  ]
})
